package com.itany.springcloud.springcloudnacosgateway6003.filter;

import com.itany.springcloud.springcloudnacosgateway6003.util.JWTUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Component
public class AccessFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request=exchange.getRequest();
        ServerHttpResponse response=exchange.getResponse();

        
        String path=request.getURI().getPath();

        System.out.println("path = " + path);

        System.out.println(request.getMethod());

        //判断路径中如果含有/user/modify/** /user/remove/**，需要鉴权
        AntPathMatcher antPathMatcher=new AntPathMatcher();

        // if(antPathMatcher.match("/user/modify/**",path)||antPathMatcher.match("/user/remove/**",path)){
        //
        // }
        //判断PUT DELETE，需要鉴权
        if(request.getMethod().matches("PUT")||request.getMethod().matches("DELETE")){
            //获得token
            HttpCookie tokenCookie=request.getCookies().getFirst("token");
            System.out.println("tokenCookie = " + tokenCookie);


            if(tokenCookie==null){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            String token=tokenCookie.getValue();


            String username=JWTUtil.getPayload("username",token);
            String password=JWTUtil.getPayload("password",token);

            System.out.println("username = " + username);
            System.out.println("password = " + password);

            if(!"abc".equals(username)||!"123".equals(password)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }


            Map<String,String> payload=new HashMap<>();

            payload.put("usenrame",username);
            payload.put("password",password);

            String jwt= JWTUtil.getJWT(payload);


            response.addCookie(ResponseCookie.from("token",jwt).build());
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
